<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------


namespace app\operation\admin;

use app\admin\admin\Base;
use app\operation\model\AdsType as AdsTypeModel;
use service\ApiReturn;
use service\Format;
use think\Db;

/**
 * 广告分类控制器
 * @package app\operation\admin
 */
class AdsType extends Base
{


    /**
     * 广告列表
     * @author 似水星辰 [2630481389@qq.com]
     * @return mixed
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder('id');
        // 数据列表
        $data_list = AdsTypeModel::where($map)->order($order)->paginate();
        $fields = [
            ['id', 'ID'],
            ['name', lang('广告位名称'), 'callback', function ($value, $data) {
                return "<a href=" . url('edit', ['id' => $data['id'], 'layer' => 1]) . " class='layeredit'>{$value}</a>";
            }, '__data__'],
            ['width', lang('图片宽度'), '', '', '', 'text-center'],
            ['height', lang('图片高度'), '', '', '', 'text-center'],
            ['create_time', lang('创建时间'), '', '', '', 'text-center'],
            ['status', lang('状态'), 'status', '', [lang('禁用'), lang('正常')], 'text-center'],
            ['right_button', lang('操作'), 'btn', '', '', 'text-center']
        ];


      
        $this->assign('tablefields', json_encode($fields, JSON_UNESCAPED_UNICODE));
        return Format::ins()//实例化
            ->hideCheckbox()
            ->addColumns($fields)//设置字段
            ->setPrimaryKey('id')
            ->setTopButtons($this->top_button)
            ->setRightButtons($this->right_button)
            ->replaceRightButton(['id' => ['lt', 7]], '', 'delete')  //前6条广告位数据不能删除
            ->setData($data_list)//设置数据
            ->fetch();//显示
    }


    public function setStatus($type = '')
    {
        $ids   = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids   = (array)$ids;
        $field = input('param.field', 'status');
        if (empty($type)) {
            $type = input('param.action');
        }

        empty($ids) && $this->error(lang('缺少主键'));

        $Model = new AdsTypeModel();

        // 主键名称
        $pk = "id";
        $result = false;
        switch ($type) {
            case 'disable': // 禁用
                $result = $Model->where($pk, 'IN', $ids)->setField($field, 0);
                Db::name('operation_ads')->where('typeid', 'IN', $ids)->setField('status', 0);
                break;
            case 'enable': // 启用
                $result = $Model->where($pk, 'IN', $ids)->setField($field, 1);
                Db::name('operation_ads')->where('typeid', 'IN', $ids)->setField('status', 1);
                break;
            case 'delete': // 删除
                $field = $Model->getTableFields($Model->getTable());
                if (in_array('is_del', $field)) {
                    $result = $Model->where($pk, 'IN', $ids)->setField('is_del', 1);
                } else {
                    $result = $Model->where($pk, 'IN', $ids)->delete();
                }

                break;
            default:
                $this->error(lang('非法操作'));
                break;
        }

        $table = strtolower(str_replace('__', '', $Model->getTable()));

        if (false !== $result) {
            // \Cache::clear();

            // 记录行为
            action_log($table.'_'.$type, $table, $ids, UID, 'ID：'.implode('、', $ids));
            $this->success(lang('操作成功'));
        } else {
            $this->error(lang('操作失败'));
        }
    }

    /**
     * 新增
     * @author 似水星辰 [2630481389@qq.com]
     * @return mixed
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $data['name'] = $this->trimAll($data['name']);
            if ($data['name'] == '') {
                $this->error(lang('广告位名称不能为空'));
            }
            if (mb_strlen($data['name'], 'utf-8') >= 20) {
                $this->error(lang('广告位名称不能超过20个字'));
            };
            // 验证
            $result = $this->validate($data, 'AdsType');
            if (true !== $result) {
                $this->error($result);
            }

            if ($type = AdsTypeModel::create($data)) {
                $this->success(lang('新增成功'), cookie('__forward__'));
            } else {
                $this->error(lang('新增失败'));
            }
        }
        $fields = [
            ['type' => 'text', 'name' => 'name', 'title' => lang('广告位名称')],
            ['type' => 'text', 'name' => 'width', 'title' => lang('图片宽度')],
            ['type' => 'text', 'name' => 'height', 'title' => lang('图片高度')],
            ['type' => 'radio', 'name' => 'status', 'title' => lang('立即启用'), 'tips' => '', 'extra' => [lang('否'), lang('是')], 'value' => 1]
        ];

        $this->assign('page_title', lang('新增广告位'));
        $this->assign('form_items', $fields);
        return $this->fetch('admin@public/add');
    }

    /**
     * 编辑
     * @param null $id 广告分类id
     * @author 似水星辰 [2630481389@qq.com]
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error(lang('缺少参数'));
        }

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $data['name'] = $this->trimAll($data['name']);
            if ($data['name'] == '') {
                $this->error(lang('广告位名称不能为空'));
            }
            if (mb_strlen($data['name'], 'utf-8') >= 20) {
                $this->error(lang('广告位名称不能超过20个字'));
            };

            // 验证
            $result = $this->validate($data, 'AdsType');
            if (true !== $result) {
                $this->error($result);
            }

            if (AdsTypeModel::update($data)) {
                $this->success(lang('编辑成功'), cookie('__forward__'));
            } else {
                $this->error(lang('编辑失败'));
            }
        }

        $info = AdsTypeModel::get($id);
        $fields = [
            ['type' => 'hidden', 'name' => 'id'],
            ['type' => 'text', 'name' => 'name', 'title' => lang('广告位名称')],
            ['type' => 'text', 'name' => 'width', 'title' => lang('图片宽度')],
            ['type' => 'text', 'name' => 'height', 'title' => lang('图片高度')],
            ['type' => 'radio', 'name' => 'status', 'title' => lang('立即启用'), 'tips' => '', 'extra' => [lang('否'), lang('是')], 'value' => 1]
        ];
        $this->assign('page_title', lang('编辑广告位'));
        $this->assign('form_items', $this->setData($fields, $info));
        return $this->fetch('admin@public/edit');
    }

    /*
     * 获取广告位宽高
     *
     */
    public function getSize()
    {
        $id = request()->param('id', 0);
        $res = Db::name('operation_ads_type')->where(['id' => $id])->field('width,height')->find();
        //如果没查到，默认400宽高
        if (empty($res)) {
            $res['width'] = 400;
            $res['height'] = 400;
        }
        return ApiReturn::r(1, $res, 'ok');
    }
}
